<template>
  <div class="ai-settings">
    <el-form :model="settings" label-width="120px">
      <el-divider content-position="left">模型配置</el-divider>
      
      <el-form-item label="AI模型">
        <el-select v-model="settings.aiModel" placeholder="请选择AI模型" style="width: 100%">
          <el-option
            v-for="model in aiModels"
            :key="model.value"
            :label="model.label"
            :value="model.value"
          >
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>{{ model.label }}</span>
              <el-tag v-if="model.tag" :type="model.tagType" size="small">{{ model.tag }}</el-tag>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="WebSocket地址">
        <el-input v-model="settings.aiUrl" placeholder="请输入WebSocket地址" />
      </el-form-item>
      
      <el-form-item label="API密钥">
        <el-input 
          v-model="settings.apiKey" 
          type="password" 
          placeholder="请输入API密钥（可选）"
          show-password
        />
      </el-form-item>

      <el-divider content-position="left">对话参数</el-divider>
      
      <el-form-item label="Temperature">
        <el-slider 
          v-model="settings.temperature" 
          :min="0" 
          :max="2" 
          :step="0.1"
          show-input
        />
        <div class="form-tip">控制回复的随机性，值越大越随机</div>
      </el-form-item>
      
      <el-form-item label="Max Tokens">
        <el-input-number 
          v-model="settings.maxTokens" 
          :min="100" 
          :max="4000" 
          :step="100"
          style="width: 100%"
        />
        <div class="form-tip">最大回复长度</div>
      </el-form-item>
      
      <el-form-item label="Top P">
        <el-slider 
          v-model="settings.topP" 
          :min="0" 
          :max="1" 
          :step="0.01"
          show-input
        />
        <div class="form-tip">核采样参数</div>
      </el-form-item>

      <el-divider content-position="left">功能开关</el-divider>
      
      <el-form-item label="语音输入">
        <el-switch v-model="settings.enableVoiceInput" />
      </el-form-item>
      
      <el-form-item label="Markdown渲染">
        <el-switch v-model="settings.enableMarkdown" />
      </el-form-item>
      
      <el-form-item label="代码高亮">
        <el-switch v-model="settings.enableCodeHighlight" />
      </el-form-item>
      
      <el-form-item label="显示推理过程">
        <el-switch v-model="settings.enableReasoning" />
      </el-form-item>
      
      <el-form-item label="自动滚动">
        <el-switch v-model="settings.autoScroll" />
      </el-form-item>

      <el-divider content-position="left">系统提示词</el-divider>
      
      <el-form-item label="系统提示词">
        <el-input
          v-model="settings.systemPrompt"
          type="textarea"
          :rows="6"
          placeholder="请输入系统提示词，用于定义AI的角色和行为..."
        />
        <div class="form-tip">自定义AI助手的角色和对话风格</div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveSettings" :loading="saving">
          保存设置
        </el-button>
        <el-button @click="resetSettings">重置</el-button>
        <el-button @click="testConnection" :loading="testing">
          测试连接
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { keyUser, valueUser } from '@/api/data'

const emit = defineEmits(['close'])

const saving = ref(false)
const testing = ref(false)

const settings = reactive({
  aiModel: '',
  aiUrl: 'wss://adminstore.saas.nbsaas.com/websocket',
  apiKey: '',
  temperature: 0.7,
  maxTokens: 2000,
  topP: 1.0,
  presencePenalty: 0.0,
  enableVoiceInput: true,
  enableMarkdown: true,
  enableCodeHighlight: true,
  enableReasoning: true,
  autoScroll: true,
  systemPrompt: '你是一个专业的ERP系统AI助手。请用清晰、友好的语言回答用户的问题，并提供实用的建议和解决方案。'
})

const aiModels = ref([
  { value: '', label: '默认模型', tag: null, tagType: null },
  { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo', tag: '推荐', tagType: 'success' },
  { value: 'gpt-4', label: 'GPT-4', tag: '最新', tagType: 'danger' },
  { value: 'gpt-4-turbo', label: 'GPT-4 Turbo', tag: '性能', tagType: 'warning' },
  { value: 'claude-3-opus', label: 'Claude 3 Opus', tag: 'Alight', tagType: 'info' },
  { value: 'claude-3-sonnet', label: 'Claude 3 Sonnet', tag: '平衡', tagType: 'info' }
])

// 加载设置
const loadSettings = async () => {
  try {
    const response = await keyUser('system_ai_settings')
    if (response && response.code === 200 && response.data) {
      let data = response.data
      if (typeof data === 'string') {
        data = JSON.parse(data)
      } else if (data.value) {
        data = JSON.parse(data.value)
      }
      Object.assign(settings, data)
      return
    }
  } catch (error) {
    console.error('从API加载AI设置失败:', error)
  }
  
  // 从本地存储加载
  try {
    const saved = localStorage.getItem('aiSettings')
    if (saved) {
      Object.assign(settings, JSON.parse(saved))
    }
  } catch (error) {
    console.error('加载AI设置失败:', error)
  }
}

// 保存设置
const saveSettings = async () => {
  saving.value = true
  try {
    // 保存到服务器
    try {
      await valueUser('system_ai_settings', JSON.stringify(settings))
    } catch (error) {
      console.error('保存到服务器失败:', error)
    }
    
    // 保存到本地存储
    localStorage.setItem('aiSettings', JSON.stringify(settings))
    
    ElMessage.success('设置保存成功')
    emit('close')
  } catch (error) {
    ElMessage.error('保存失败')
    console.error(error)
  } finally {
    saving.value = false
  }
}

// 重置设置
const resetSettings = () => {
  Object.assign(settings, {
    aiModel: '',
    aiUrl: 'wss://adminstore.saas.nbsaas.com/websocket',
    apiKey: '',
    temperature: 0.7,
    maxTokens: 2000,
    topP: 1.0,
    presencePenalty: 0.0,
    enableVoiceInput: true,
    enableMarkdown: true,
    enableCodeHighlight: true,
    enableReasoning: true,
    autoScroll: true,
    systemPrompt: '你是一个专业的ERP系统AI助手。请用清晰、友好的语言回答用户的问题，并提供实用的建议和解决方案。'
  })
  ElMessage.info('已重置为默认设置')
}

// 测试连接
const testConnection = async () => {
  testing.value = true
  try {
    const ws = new WebSocket(settings.aiUrl)
    
    const timeout = setTimeout(() => {
      ws.close()
      ElMessage.error('连接超时')
      testing.value = false
    }, 5000)
    
    ws.onopen = () => {
      clearTimeout(timeout)
      ws.close()
      ElMessage.success('连接成功')
      testing.value = false
    }
    
    ws.onerror = () => {
      clearTimeout(timeout)
      ElMessage.error('连接失败')
      testing.value = false
    }
  } catch (error) {
    ElMessage.error('连接测试失败')
    testing.value = false
  }
}

onMounted(() => {
  loadSettings()
})
</script>

<style scoped lang="scss">
.ai-settings {
  padding: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
